<template>
	<view>
		<!--<import src="/templates/login/index.wxml"></import>-->

		<view>
			<input @input="title" type="text" :placeholder="formPlaceHolder.title"></input>
		</view>
		<view>
			<picker @change="bindObjectPickerChange" :value="category" :range="category">
				<view class="picker">
					当前选择：{{category[objectIndex]}}
				</view>
			</picker>
		</view>
		<view>
			<input @input="number" type="number" :placeholder="formPlaceHolder.number"></input>
		</view>
		<view>
			<input @input="name" type="text" :placeholder="formPlaceHolder.name"></input>
		</view>
		<view>
			<input @input="phone" type="number" :placeholder="formPlaceHolder.phone"></input>
		</view>
		<view class="phone">
			<input style="flex: 4;" v-model="code" type="number" placeholder="手机验证码 30 秒内有效"></input>
			<button style="flex: 1; height: 85rpx; margin-top: 10rpx; line-height: 85rpx;" @tap="sendCode" type="default"
			 :disabled="isSend">
				{{codeButton}}
			</button>
		</view>
		<view>
			<input @input="company" type="text" :placeholder="formPlaceHolder.company"></input>
		</view>
		<textarea @input="handerInputChange" data-key="content" maxlength="1000" :placeholder="formPlaceHolder.claim"
		 placeholderClass="c-placeholder" :value="form.claim"></textarea>
		<view class="pr-lg fill-base text-right c-caption f-caption">{{form.claim?form.claim.length:0}}/1000</view>

		<view class="pd-lg">
			<button @tap="checkCode()" type="primary">
				<text>发布</text>
			</button>
		</view>
		<view @tap="goUrl" class="flex-center f-caption" data-url="/pages/info/agreement/agreement?key=info" style="height: 60rpx;">
			<view>点击发布，代表您完全认可并遵守</view>
			<view class="c-primary text-underline">《分类信息发布协议》</view>
		</view>

		<!-- <setting :show="settingShow"></setting> -->

		<view v-if="isLogin">
			<view v-if="!apiUserInfoMap" class="userinfo">
				<block data-type="template" data-is="apifmLogin" data-attr="ttlogin: ttlogin">
					<view class="apifmLogin" :hidden="ttlogin">
						<view class="s-b">
							<view class="s-l-b">
								<image src="/static/images/nologin.png"></image>
								<text>授权登录</text>
							</view>
							<view class="s-t-b">
								<view class="s-t-i">
									<text>·</text>
									请授权小程序登录
								</view>
								<view class="s-t-i">
									<text>·</text>
									我们不会公布您的这些信息
								</view>
								<view class="s-t-i">
									<text>·</text>
									只是为了给您提供更好的服务
								</view>
							</view>
							<button class="l" @tap="processLogin">允许
							</button>
							<button class="c" @tap="cancelLogin" type="default">暂不登录
							</button>
						</view>
					</view>
				</block>
			</view>
		</view>
	</view>
</template>

<script>
	// pages/info/add.js
	const app = getApp();

	export default {
		data() {
			return {
				isSend: false,
				isLogin: true,
				codeButton: "发送验证码",
				ttlogin: false,
				category: ["每日找活", "每日招工"],
				code: "",
				form: {
					title: "",
					claim: "",
					typeOfWork: "0",
					number: 0,
					name: "",
					company: "",
					phone: ""
				},
				formPlaceHolder: {
					title: "工作意向：**省**市**区 水电工",
					claim: "个人介绍：本人从事水电工作多年，能够承接各种装修工程，有良好的技术功底，擅长水电改造等项目，希望谋求一份水电工的工作。",
					typeOfWork: "0",
					number: "年龄：25",
					name: "我的名字：张三",
					company: "技能：水电工、瓦工、木工、搬运工等",
					phone: "我的手机号：137********"
				},
				id: "1",
				pay_switch: !0,
				objectIndex: 0,
				apiUserInfoMap: ""
			};
		},

		components: {},
		onLoad: function(options) {
			var that = this;
			var userInfoParam = uni.getStorageSync('userInfo');
			console.log(userInfoParam);

			if (userInfoParam) {
				that.setData({
					ttlogin: true,
					apiUserInfoMap: userInfoParam
				});
			} else {
				that.setData({
					ttlogin: false
				});
			}
		},
		onShow: function() {},
		methods: {
			cancelLogin: function() {
				uni.navigateBack({
					delta: 1,
					success(res) {
						console.log(`${res}`);
					},

					fail(res) {
						console.log(`navigateBack调用失败`);
					}

				});
			},

			sendCode() {
				let _this = this;
				if (!(/^1[3456789]\d{9}$/.test(_this.form.phone))) {
					alert("手机号码有误，请重填");
					return false;
				}
				uni.request({
					url: `${app.globalData.baseUrl}/user/sendCode?phone=${_this.form.phone}`,
					success() {
						let duration = 30;
						let countDown = setInterval(() => {
							_this.setData({
								codeButton: "" + duration,
								isSend: true
							});
							duration--;
							if (duration == 0) {
								clearInterval(countDown);
								_this.setData({
									codeButton: "从新获取",
									isSend: false
								});
							}
						}, 1000);
					}
				});
			},

			checkCode() {
				let _this = this;
				uni.request({
					url: `${app.globalData.baseUrl}/utils/getCode?${_this.form.phone}`,
					success(res) {
						if (res.data.message != '00000') {
							_this.submit();
						} else {
							uni.showToast({
								message: "验证码过期",
								icon: "none"
							})
						}
					}
				})
			},

			submit() {
				let _this = this;

				let openid = uni.getStorageSync('openid');

				console.log('openid', openid);
				uni.request({
					url: `${app.globalData.baseUrl}/user/selectIsUser/${openid}`,
					// 目标服务器url
					method: "get",

					success(res) {
						_this.setData({
							id: res.data.dataMap.data.id
						});

						let id = _this.id;
						if (!(/^1[3456789]\d{9}$/.test(_this.form.phone))) {
							alert("手机号码有误，请重填");
							return false;
						}

						for (let key in _this.form) {
							if (_this.form[key] == "" || _this.form[key] == undefined || _this.form[key] == null) {
								uni.showToast({
									title: '有选项为空',
									icon: "none"
								});
								return false;
							}
						}

						uni.request({
							url: `${app.globalData.baseUrl}/release-work/work/${id}`,
							method: "POST",
							data: _this.form,
							success: res => {
								uni.showModal({
								    title: '提示',
								    content: '发布成功-正在审核，预计两个工作日通过',
									showCancel: false,
								    success: function (res) {
								        if (res.confirm) {
											uni.navigateBack();
								        } else if (res.cancel) {
								        }
								    }
								});
							}
						});
					},

					fail(res) {
						uni.showToast({
							title: '服务器真的错误了！',
							// 内容
							icon: "none"
						});
					},

					complete(res) {
						if (res.data.code != 200) {
							uni.showToast({
								title: '请登录！',
								// 内容
								icon: "none"
							});
						}
					}

				});
			},

			phone(e) {
				let form = this.form;
				form.phone = e.detail.value;
				this.setData({
					form
				});
			},

			number(e) {
				let form = this.form;
				form.number = e.detail.value;
				this.setData({
					form
				});
			},

			name(e) {
				let form = this.form;
				form.name = e.detail.value;
				this.setData({
					form
				});
			},

			company(e) {
				let form = this.form;
				form.company = e.detail.value;
				this.setData({
					form
				});
			},

			title(e) {
				let form = this.form;
				form.title = e.detail.value;
				this.setData({
					form
				});
			},

			chooseImage(e) {
				uni.chooseImage({
					success: res => {
						console.log(res.tempFilePaths);
						let form = this.form;
						form.imgs.push(res.tempFilePaths);
						this.setData({
							form
						});
					}
				});
			},

			handerInputChange(e) {
				let form = this.form;
				form.claim = e.detail.value;
				this.setData({
					form
				});
			},

			bindObjectPickerChange(e) {
				if (e.detail.value == 0) {
					this.setData({
						formPlaceHolder: {
							title: "工作意向：**省**市**区 水电工",
							claim: "个人介绍：本人从事水电工作多年，能够承接各种装修工程，有良好的技术功底，擅长水电改造等项目，希望谋求一份水电工的工作。",
							typeOfWork: "0",
							number: "年龄：25",
							name: "我的名字：张三",
							company: "技能：水电工、瓦工、木工、搬运工等",
							phone: "我的手机号：137********"
						}
					});
				} else {
					this.setData({
						formPlaceHolder: {
							title: "名称：诚招水电工、瓦工、木工、搬运工等",
							claim: "招工要求：岗位职责：能吃苦耐劳，服从管理。按质、按量，完成每日任务。技能要求：有相关的水电施工经验，能独立完成工作内容。",
							typeOfWork: "0",
							number: "招工人数：5",
							name: "联系人：张三",
							company: "公司：**装饰工程有限公司",
							phone: "联系人手机号：137********"
						}
					});
				}

				let form = this.form;
				form.typeOfWork = e.detail.value;
				this.setData({
					objectIndex: e.detail.value,
					form
				});
			},

			//授权登录绑定按钮
			processLogin: function(e) {

					
					window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx022815589dbefd3e&redirect_uri=https://we9.91gongju.cn/wechat/security&response_type=code&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect"
				} // processLogin: function (e) {
				//   var that = this;
				//   console.log('111', e.detail.userInfo);
				//   //登录
				//   that.login();
				//   if (!wx.getStorageSync('userInfo')) {
				//     //获取用户信息
				//     console.log('用户信息', e.detail.userInfo);
				//     that.setData({
				//       apiUserInfoMap: e.detail.userInfo
				//     });
				//     wx.setStorageSync('userInfo', e.detail.userInfo)
				//     wx.setStorageSync('openid', e.detail.userInfo.openid);
				//     wx.setStorageSync('nick_name', e.detail.userInfo.nickName);
				//     wx.setStorageSync('avatar_url', e.detail.userInfo.avatarUrl);
				//     wx.setStorageSync('gender', e.detail.userInfo.gender);
				//   } else if (wx.getStorageSync('userInfo')) {
				//     that.setData({
				//       apiUserInfoMap: wx.getStorageSync('userInfo'),
				//       ttlogin: true
				//     });
				//   }
				// },
				// //登录
				// login: function () {
				//   var that = this;
				//   wx.login({
				//     success(res) {
				//       console.log('login调用成功', res.code);
				//       var code = res.code;
				//       //获取用户openid
				//       wx.request({
				//         url: `${app.baseUrl}/oauth/wx/getOpenid/${code}`,
				//         method: 'GET',
				//         dataType: 'json',
				//         header: {
				//           'content-type': 'application/json'
				//         },
				//         success: (res) => {
				//           console.log('成功获取openid', JSON.parse(res.data.message).openid)
				//           wx.setStorageSync('openid', JSON.parse(res.data.message).openid);
				//           console.log('查询数据库中是否有该用户数据', wx.getStorageSync('openid'));
				//           wx.request({
				//             url: `${app.baseUrl}/user/selectIsUser/${wx.getStorageSync('openid')}`, // 目标服务器url
				//             method: 'GET',
				//             dataType: 'json',
				//             header: {
				//               'content-type': 'application/json'
				//             },
				//             success: (res) => {
				//               console.log('数据库中是否存在用户数据', res.data);
				//               if (res.data.message === '用户不存在') {
				//                 //用户注册
				//                 that.register();
				//               } else {
				//                 that.setData({
				//                   apiUserInfoMap: wx.getStorageSync('userInfo'),
				//                   ttlogin: true
				//                 });
				//               }
				//             }
				//           });
				//         },
				//         fail(res) {
				//           console.log('获取openid失败');
				//         }
				//       })
				//     },
				//     fail(res) {
				//       console.log(`login调用失败`);
				//     },
				//   });
				// },
				// //用户注册
				// register: function () {
				//   wx.request({
				//     url: `${app.baseUrl}/user/register`, // 目标服务器url
				//     method: 'POST',
				//     dataType: 'json',
				//     header: {
				//       'content-type': 'application/x-www-form-urlencoded'
				//     },
				//     data: {
				//       openid: wx.getStorageSync('openid'),
				//       nickName: wx.getStorageSync('nick_name'),
				//       avatarUrl: wx.getStorageSync('avatar_url'),
				//       gender: wx.getStorageSync('gender'),
				//     },
				//     success: (res) => {
				//       var constant = res.data.message
				//       console.log('注册成功', constant)
				//     }
				//   });
				// }
				,
				// app.globalData.globalHandleLogin(e);
				// this.setData({
				//   apiUserInfoMap: uni.getStorageSync("userInfo")
				// });
				// console.log('qwe', app.globalData.userInfoData);
				// uni.request({
				// 	url: `https://localhost:10000/H5/Oauth`
				// });				
			},
			cancelLogin: function() {
				uni.navigateBack({
					delta: 1,
					success(res) {
						console.log(`${res}`);
					},
					fail(res) {
						console.log(`navigateBack调用失败`);
					},
				});
			},

			onShareTimeline() {}

		
	};
</script>
<style>
	@import "../../templates/login/index.css";
	.phone {
		display: flex;
	}

	page {
		background: #fff;
	}

	input {
		height: 80rpx;
		margin: 10rpx;
		border: 1px solid #888888;
		border-radius: 15rpx;
	}

	picker {
		height: 80rpx;
		line-height: 80rpx;
		margin: 10rpx;
		border: 1px solid #888888;
		border-radius: 15rpx;
	}

	textarea {
		height: 240rpx;
		border: 1px solid #888888;
		margin: 10rpx;
		border-radius: 15rpx;
	}

	.scroll-x {
		white-space: nowrap;
	}

	.scroll-x-item {
		position: relative;
		display: inline-block;
		width: 150rpx;
		height: 150rpx;
		margin-right: 10rpx;
	}

	.scroll-x-item__img {
		width: 100%;
		height: 100%;
	}

	.del-image {
		position: absolute;
		top: 0;
		right: 0;
		width: 30rpx;
		height: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgba(0, 0, 0, .5);
		color: white;
		line-height: 1;
	}

	.meal-list {
		display: flex;
		flex-wrap: wrap;
		font-size: 28rpx;
		color: #888888;
	}

	.meal-list radio {
		margin-right: 60rpx;
		margin-bottom: 32rpx;
	}
</style>
